<?php

use Nette\Application\UI\Form;

class ProfilePresenter extends BasePresenter
{

	public function renderDefault()
	{
		$userModel = $this->context->models->users;
		$user = $userModel->getUser(array('id' => $this->user->id));
		$this['profileForm']->setDefaults($user);
	}

	protected function createComponentProfileForm($name)
	{
		$authModel = $this->context->models->authorization;
		$departmentModel = $this->context->models->department;
		$usersModel = $this->context->models->users;

		$form = new Form($this, $name);
		$form->addGroup('Změna osobních údajů');
		$form->addText('name', 'Jméno:')
				->setRequired('Jméno je povinné');
		$form->addText('surname', 'Příjmení:')
				->setRequired('Příjmení je povinné');
		$form->addText('email', 'E-mail:')
				->addCondition(Form::FILLED)
				->addRule(Form::EMAIL, 'Byl zadán neplatný e-mail');
		$form->addText('login', 'Login:');
		$form->addGroup('Změna hesla');
		$form->addPassword('password_old', 'Původní heslo:');
		$form->addPassword('password', 'Heslo:');
		$form['password_old']->addConditionOn($form['password'], Form::FILLED)
				->addRule(Form::FILLED,'Pro změnu hesla vyplňte původní heslo');
		$form->addPassword('password_again', 'Heslo znovu:')
				->addConditionOn($form['password'], Form::FILLED)
				->addRule(Form::EQUAL, 'Hesla se musí shodovat.', $form['password']);
		$form->setCurrentGroup();
		$form->addSubmit('save', 'Uložit');

		$form->onSuccess[] = callback($this, 'profileFormSubmitted');
		return $form;
	}

	public function profileFormSubmitted($form)
	{
		$values = $form->getValues();
		$values['id'] = $this->user->id;
		unset($values['password_again']);
		if ($values['password'] == '')
		{
			unset ($values['password']);
		}
		try {
			$this->context->models->users->editProfile($values);
			$this->flashMessage('Váš profil byl úspěšně uložen.');
			//$this->redirect('this');
		}catch(Nette\Security\AuthenticationException $e){
			$this->flashMessage('Nastala chyba při ukládání profilu.','error');
			$this->flashMessage($e->getMessage(),'error');
		}
	}

}